<?php
if(isset($_POST['action']))
{
    $db = new Database();
    $page = $_POST['page'];
    $cur_page = $page;
    $page -= 1;
    $per_page = 10; // Per page
    $previous_btn = true;
    $next_btn = true;
    $first_btn = true;
    $last_btn = true;
    $start = $page * $per_page;
    $action = $_POST['action'];
    $finaldata = "<table class='table_data'>
                     <thead>
                         <tr>
                              <th>User</th>
                              <th>Action</th>
                              <th>Affected Table</th>
                              <!--th>Affected Record</th-->
                              <th>Date and Time</th>
                         </tr>
                     </thead>
                     <tbody>";
    if($action=="searchAudit")
    {
        $value = $_POST['Name'];
	    $userName = $db->query("SELECT * FROM users WHERE Firstname LIKE '%$value%' OR Lastname LIKE '%$value%'","row");
		$userID = $userName['userID'];
	    $auditAction = $db->query("SELECT * FROM action WHERE action LIKE '%$value%'","row");
		$actionID = $auditAction['id'];
	$audit_trail = $db->query("SELECT * FROM audit_trail WHERE userID='$userID' OR actionID='$actionID' OR affectedTable LIKE '%$value%' LIMIT $start, $per_page","array");
	$count = $db->query("SELECT * FROM audit_trail WHERE  userID='$userID' OR actionID='$actionID' OR affectedTable LIKE '%$value%'","numrows");
        $no_of_paginations = ceil($count / $per_page);
    }elseif($action=="default"){
	$audit_trail = $db->query("SELECT * FROM audit_trail LIMIT $start, $per_page","array");
	$count = $db->query("SELECT * FROM audit_trail ","numrows");
        $no_of_paginations = ceil($count / $per_page);
    }
    if($count>0){
      foreach($audit_trail as $row_action)
	{
	    $userID = $row_action['userID'];
		$userName = $db->query("SELECT * FROM users WHERE userID='$userID'","row");
	    $actionID = $row_action['actionID'];
		$auditAction = $db->query("SELECT * FROM action WHERE id='$actionID'","row");
	    
	$finaldata.= '<tr>
	    <td>'.$userName['Firstname']. ' ' .$userName['Lastname'].'</td>
	    <td>'.$auditAction['action'].'</td>
	    <td>'.$row_action['affectedTable'].'</td>
	    
	    <td>'.$row_action['datetime'].'</td>
	</tr>';
	}
        //pagination
        pagination($cur_page,$page,$per_page,$start,$previous_btn,$next_btn,$first_btn,$last_btn,$no_of_paginations,$finaldata,$count,$action,$value);
    }else{
        $finaldata.="<tr><td colspan='9'><center>No Record Found</center></td></tr>";
        echo $finaldata;
    }
}
?>
